package com.relsell.utility;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.relsell.admin.DbHelper;
import com.relsell.pointofsales.R;
import com.relsell.view.Manager.TabsAdapter;

public class UtilitySingleTon {
	private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	private static UtilitySingleTon thisObj;
	private TabHost mTabHost;
	private ViewPager mViewPager;
	private TabsAdapter mTabsAdapter;
	private String gCMRegId;
	private int mYear = 2014;
	private int mMonth = 3;
	private View mMapView;
	private GoogleMap map;

	private UtilitySingleTon() {

	}

	public static UtilitySingleTon getInstance() {
		if (thisObj == null) {
			thisObj = new UtilitySingleTon();
		}
		return thisObj;
	}

	/**
	 * Check the device to make sure it has the Google Play Services APK. If it
	 * doesn't, display a dialog that allows users to download the APK from the
	 * Google Play Store or enable it in the device's system settings.
	 */
	public boolean checkPlayServices(Context context) {
		int resultCode = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(context);
		if (resultCode != ConnectionResult.SUCCESS) {
			if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
				GooglePlayServicesUtil.getErrorDialog(resultCode,
						(Activity) context, PLAY_SERVICES_RESOLUTION_REQUEST)
						.show();
			} else {
				if (AppVars.isLogEnabled) {
					Log.i(AppVars.LOG_TAG, "This device is not supported.");
				}
			}
			return false;
		}
		return true;
	}

	public TabHost getTabHost() {
		return mTabHost;
	}

	public void setTabHost(TabHost mTabHost) {
		this.mTabHost = mTabHost;
	}

	public ViewPager getViewPager() {
		return mViewPager;
	}

	public void setViewPager(ViewPager mViewPager) {
		this.mViewPager = mViewPager;
	}

	public TabsAdapter getTabsAdapter() {
		return mTabsAdapter;
	}

	public void setTabsAdapter(TabsAdapter mTabsAdapter) {
		this.mTabsAdapter = mTabsAdapter;
	}

	public String getgCMRegId() {
		return gCMRegId;
	}

	public void setgCMRegId(String gCMRegId) {
		this.gCMRegId = gCMRegId;
	}

	public Date getDateFromString(String dateStr) {
		Date date = null;
		String dtStart = dateStr;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
		try {
			date = format.parse(dtStart);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

	public int getYearNo(Date date) {
		int res = 0;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		res = c.get(Calendar.YEAR);
		return res;
	}

	public int getWeekNo(Date date) {
		int res = 0;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		res = c.get(Calendar.WEEK_OF_MONTH);
		return res;
	}

	public int getDayNo(Date date) {
		int res = 0;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		res = c.get(Calendar.DAY_OF_WEEK);
		return res;
	}

	public int getMonthNo(Date date) {
		int res = 0;
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		res = c.get(Calendar.MONTH);
		return res;
	}

	public ArrayList<UserPin> getFilterUserPinListForYear(
			ArrayList<UserPin> list, int Year) {
		ArrayList<UserPin> filteredList = new ArrayList<UserPin>();
		if (list != null) {
			for (UserPin localObj : list) {
				if (Year == localObj.getYear()) {
					filteredList.add(localObj);
				}
			}
		}
		return filteredList;
	}

	public ArrayList<UserPin> getFilterUserPinListForMonth(
			ArrayList<UserPin> list, int month) {
		ArrayList<UserPin> filteredList = new ArrayList<UserPin>();
		if (list != null) {
			for (UserPin localObj : list) {
				if (month == localObj.getMonth()) {
					filteredList.add(localObj);
				}
			}
		}
		return filteredList;
	}

	public void printList(ArrayList<UserPin> list) {
		for (UserPin localObj : list) {
			if (AppVars.isLogEnabled) {
				Log.d(AppVars.LOG_TAG, "User Pin  data ");
				Log.d(AppVars.LOG_TAG, "User is " + localObj.getUserId());
				Log.d(AppVars.LOG_TAG, "Year is " + localObj.getYear());
				Log.d(AppVars.LOG_TAG, "Month is " + localObj.getMonth());
				Log.d(AppVars.LOG_TAG, "Latitude is " + localObj.getLatitude());
				Log.d(AppVars.LOG_TAG,
						"Longitude is " + localObj.getLongitude());
			}
		}

	}

	public void setUserPinYearDate(ArrayList<UserPin> list) {
		for (UserPin localObj : list) {
			Date date = getDateFromString(localObj.getDateStr());
			int year = getYearNo(date);
			if (AppVars.isLogEnabled) {
				// Log.i(AppVars.LOG_TAG,"Year is "+year);
			}
			int month = getMonthNo(date);
			if (AppVars.isLogEnabled) {
				// Log.i(AppVars.LOG_TAG,"Month is "+month);
			}
			int week = getWeekNo(date);
			if (AppVars.isLogEnabled) {
				// Log.i(AppVars.LOG_TAG,"Week is "+week);
			}
			localObj.setYear(year);
			localObj.setMonth(month);
			localObj.setWeek(week);
		}
	}

	public void createDummyArrayListofUserPin(ArrayList<UserPin> list,
			Context context) {
		AppVars.sUserPinList.add(new UserPin("0", "1", "30.43509989242377",
				"77.73051012307405", "2014-03-03 18:29:46", "60"));
		AppVars.sUserPinList.add(new UserPin("0", "1", "30.43509989242377",
				"77.73051012307405", "2014-03-04 18:29:46", "40"));
		AppVars.sUserPinList.add(new UserPin("0", "1", "30.43509989242377",
				"77.73051012307405", "2014-03-05 18:29:46", "50"));
		AppVars.sUserPinList.add(new UserPin("0", "1", "30.43509989242377",
				"77.73051012307405", "2014-03-06 18:29:46", "60"));
		AppVars.sUserPinList.add(new UserPin("0", "1", "30.43509989242377",
				"77.73051012307405", "2014-03-07 18:29:46", "70"));
		AppVars.sUserPinList.add(new UserPin("1", "2", "30.444973948168244",
				"77.74658996611834", "2013-03-05 18:29:46", "60"));
		AppVars.sUserPinList.add(new UserPin("2", "3", "30.437833070086825",
				"77.74405796080828", "2012-03-05 18:29:46", "40"));
		AppVars.sUserPinList.add(new UserPin("3", "4", "30.43509989242377",
				"77.73051012307405", "2014-02-05 18:29:46", "60"));
		AppVars.sUserPinList.add(new UserPin("4", "5", "30.444973948168244",
				"77.74658996611834", "2013-03-05 18:29:46", "60"));
		AppVars.sUserPinList.add(new UserPin("5", "6", "30.437833070086825",
				"77.74405796080828", "2012-03-10 18:29:46", "30"));
		AppVars.sUserPinList.add(new UserPin("7", "8", "30.43509989242377",
				"77.73051012307405", "2014-03-05 18:29:46", "40"));
		AppVars.sUserPinList.add(new UserPin("8", "9", "30.444973948168244",
				"77.74658996611834", "2013-03-05 18:29:46", "60"));
		AppVars.sUserPinList.add(new UserPin("9", "10", "30.437833070086825",
				"77.74405796080828", "2012-03-05 18:29:46", "60"));
		setUserPinYearDate(AppVars.sUserPinList);
		DbHelper db = new DbHelper(context);
		db.open();
		for (UserPin localObj : list) {
			String date = localObj.getDateStr();
			String userId = localObj.getUserId();
			String lat = localObj.getLatitude();
			String lng = localObj.getLongitude();
			String username = "username";
			String targetAchieved = localObj.getTargedAchieved();
			db.insert_map_data(date, userId, lat, lng, username, "product",
					targetAchieved);
		}
		db.close();
		Toast.makeText(context, "inserted", Toast.LENGTH_SHORT).show();
	}

	public void createDummyArrayListofUserPin(Context context) {
		AppVars.sUserPinList.clear();
		DbHelper db = new DbHelper(context);
		db.open();
		Cursor c = db.read_map_data();
		int count = c.getCount();
		for (int i = 0; i < count; i++) {
			c.moveToNext();
			String userId = c.getString(c
					.getColumnIndex(DbHelper.FIELD_USER_ID));
			double latitude = c.getDouble(c
					.getColumnIndex(DbHelper.FIELD_LATITUDE));
			double longitude = c.getDouble(c
					.getColumnIndex(DbHelper.FIELD_LONGITUDE));
			String id = c.getString(c.getColumnIndex(DbHelper.FIELD_ID));
			String dateStr = c.getString(c
					.getColumnIndex(DbHelper.FIELD_SELLING_DATA));
			String targedAchieved = c.getString(c
					.getColumnIndex(DbHelper.FIELD_TARGET_ACHIEVED_DATA));
			UserPin localObj = new UserPin(id, userId, "" + latitude, ""
					+ longitude, dateStr, targedAchieved);
			AppVars.sUserPinList.add(localObj);
		}
		db.close();
		setUserPinYearDate(AppVars.sUserPinList);
	}

	public void prepareUserPinList(ArrayList<UserPin> list, Context context) {
		// createDummyArrayListofUserPin(AppVars.sUserPinList,context);
		createDummyArrayListofUserPin(context);
	}

	public void createDummyFilteredArrayList(ArrayList<UserPin> list) {
		AppVars.sFilteredUserPinList = getFilterUserPinListForYear(list, mYear);
		AppVars.sFilteredUserPinList = getFilterUserPinListForMonth(
				AppVars.sFilteredUserPinList, mMonth);
	}

	public View getMapView() {
		return mMapView;
	}

	public void setMapView(View mMapView) {
		this.mMapView = mMapView;
	}

	public void drawMapOptions(GoogleMap localMap, FragmentActivity activity,
			ArrayList<UserPin> userPinList) {
		if (localMap != null) {
		    localMap.clear();
		}
		LatLng latLongInitial = null;
		printList(userPinList);
		if (localMap != null) {
			for (UserPin localObj : userPinList) {
				Double latitude = Double.parseDouble(localObj.getLatitude());
				Double longitude = Double.parseDouble(localObj.getLongitude());
				LatLng latLong = new LatLng(latitude, longitude);
				localMap.addMarker(new MarkerOptions().position(latLong));
				latLongInitial = latLong;
			}
			localMap.setInfoWindowAdapter(new MyInfoWindowAdapter(activity));
			localMap.getUiSettings().setRotateGesturesEnabled(false);
			localMap.getUiSettings().setScrollGesturesEnabled(false);
			if (latLongInitial != null) {
			    localMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
					latLongInitial, 15));
			} else {
				Toast.makeText(activity, "Reports are yet to be arrived", Toast.LENGTH_LONG).show();
			}
			localMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
		}
	}


	public GoogleMap getMap() {
		return map;
	}

	public void setMap(GoogleMap map) {
		this.map = map;
	}

	class MyInfoWindowAdapter implements InfoWindowAdapter {

		Context mContext;
		FragmentActivity activity;

		public MyInfoWindowAdapter(Context context) {
			this.mContext = context;
		}

		public MyInfoWindowAdapter(FragmentActivity activity) {
			this.activity = activity;
		}

		@Override
		public View getInfoContents(Marker marker) {
			UserPin tappedUserPin = null;
			LayoutInflater li = null;
			if (mContext != null) {
				li = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			} else {
				li = (LayoutInflater) activity.getLayoutInflater();
			}
			HashMap<String, String> hMap = new HashMap<String, String>();
			View v = li.inflate(R.layout.custom_info_marker, null);
			LatLng ll = marker.getPosition();
			TextView dayOneTarget = (TextView) v.findViewById(R.id.textView2);
			TextView dayTwoTarget = (TextView) v.findViewById(R.id.textView4);
			TextView dayThreeTarget = (TextView) v.findViewById(R.id.textView6);
			TextView dayFourTarget = (TextView) v.findViewById(R.id.textView8);
			TextView dayFiveTarget = (TextView) v.findViewById(R.id.textView10);
			HashMap<Integer, ArrayList<Integer>> listMap = new HashMap<Integer, ArrayList<Integer>>();
			for (UserPin localObj : AppVars.sUserPinList) {

				double latitudeFromObj = Double.parseDouble(localObj
						.getLatitude());
				double longitudeFromObj = Double.parseDouble(localObj
						.getLongitude());
				String dfLat1 = new DecimalFormat("#.###")
						.format(latitudeFromObj);
				String dfLat2 = new DecimalFormat("#.###").format(ll.latitude);
				String dfLong1 = new DecimalFormat("#.###")
						.format(longitudeFromObj);
				String dfLong2 = new DecimalFormat("#.###")
						.format(ll.longitude);
				if (dfLat1.equals(dfLat2) && dfLong1.equals(dfLong2)) {
					tappedUserPin = localObj;
					Date date = UtilitySingleTon.getInstance()
							.getDateFromString(tappedUserPin.getDateStr());

					int weekday = UtilitySingleTon.getInstance().getDayNo(date);
					ArrayList<Integer> list = null;
					switch (weekday) {
					case 2:
						list = listMap.get(0);
						if (list == null) {
							listMap.put(0, new ArrayList<Integer>());
							list = listMap.get(0);
						}
						list.add(Integer.parseInt(tappedUserPin
								.getTargedAchieved()));
						listMap.put(0, list);
						int val2 = getMaximumFromList(list);
						if (val2 >= 50) {
							dayOneTarget.setTextColor(Color.GREEN);
						} else {
							dayOneTarget.setTextColor(Color.RED);
						}
						dayOneTarget.setText("" + val2);
						break;
					case 3:
						list = listMap.get(1);
						if (list == null) {
							listMap.put(1, new ArrayList<Integer>());
							list = listMap.get(1);
						}
						list.add(Integer.parseInt(tappedUserPin
								.getTargedAchieved()));
						listMap.put(1, list);
						int val3 = getMaximumFromList(list);
						if (val3 >= 50) {
							dayTwoTarget.setTextColor(Color.GREEN);
						} else {
							dayTwoTarget.setTextColor(Color.RED);
						}
						dayTwoTarget.setText("" + val3);
						break;
					case 4:
						list = listMap.get(2);
						if (list == null) {
							listMap.put(2, new ArrayList<Integer>());
							list = listMap.get(2);
						}
						list.add(Integer.parseInt(tappedUserPin
								.getTargedAchieved()));
						listMap.put(2, list);
						int val4 = getMaximumFromList(list);
						if (val4 >= 50) {
							dayThreeTarget.setTextColor(Color.GREEN);
						} else {
							dayThreeTarget.setTextColor(Color.RED);
						}
						dayThreeTarget.setText("" + val4);
						break;
					case 5:
						list = listMap.get(3);
						if (list == null) {
							listMap.put(3, new ArrayList<Integer>());
							list = listMap.get(3);
						}
						list.add(Integer.parseInt(tappedUserPin
								.getTargedAchieved()));
						listMap.put(3, list);
						int val5 = getMaximumFromList(list);
						if (val5 >= 50) {
							dayFourTarget.setTextColor(Color.GREEN);
						} else {
							dayFourTarget.setTextColor(Color.RED);
						}
						dayFourTarget.setText("" + val5);
						break;
					case 6:
						list = listMap.get(4);
						if (list == null) {
							listMap.put(4, new ArrayList<Integer>());
							list = listMap.get(4);
						}
						list.add(Integer.parseInt(tappedUserPin
								.getTargedAchieved()));
						listMap.put(4, list);
						int val6 = getMaximumFromList(list);
						if (val6 >= 50) {
							dayFiveTarget.setTextColor(Color.GREEN);
						} else {
							dayFiveTarget.setTextColor(Color.RED);
						}
						dayFiveTarget.setText("" + val6);
						break;
					}
				}
			}

			TextView title = (TextView) v.findViewById(R.id.userdata);
			title.setText("User is " + tappedUserPin.getUserId());

			return v;
		}

		@Override
		public View getInfoWindow(Marker marker) {
			View v = null;
			return v;
		}

	}

	public int getMaximumFromList(ArrayList<Integer> list) {
		int pivot = 0;
		for (Integer local : list) {
			if (pivot < local) {
				pivot = local;
			}
		}
		return pivot;
	}

}
